<template>
    <div class="page-wrap">
        <!-- <div style="color: rgb(27, 76, 184);margin-bottom: 15px">
            <div class="addressIcon"></div>
            <span>当前位置：</span>
            <span style="cursor: pointer" @click="returnCourse"> -->
                <!-- 课程管理 -->
                <!-- {{ pageTitle }}管理 -->
            <!-- </span>
            <Icon type="ios-arrow-forward" color="rgb(27, 76, 184)" size="16" />
            <span style="color: #333">{{titleText}}</span>
        </div> -->
        <div class="page-content" :style="{height:contentHei}">
            <div class="img-header">
                <div style="font-weight: 700;font-size: 18px">{{titleText}}</div>
            </div>
            <Divider />
            <div class="content-wrap">
                <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="120" style="width: 500px">
                    <FormItem label="课程名称" prop="ccname">
                        <Input v-model.trim="formValidate.ccname" placeholder='不能包含下列任意英文字符 \ / : * ? " < > |，名称长度为1-128个字符'></Input>
                    </FormItem>
                   <FormItem label="方向" prop="direction">
                    <i-select v-model="formValidate.direction" placeholder="方向" @on-change="changeDirection">
                      <i-option v-for="(value,key) in expClassifyLevel1" :value="value.dictid" :key="key">{{value.dictname}}</i-option>
                    </i-select>
                  </FormItem>
                  <FormItem label="类型" prop="typeCode">
                    <i-select v-model="formValidate.typeCode" placeholder="类型" @on-change="changeTypeCode">
                      <i-option v-for="(value,key) in expClassifyLevel2" :value="value.dictid" :key="key">{{value.dictname}}</i-option>
                    </i-select>
                  </FormItem> 
                  <FormItem label="标签" prop="labels">
                                <Select filterable clearable v-model="formValidate.labels" placeholder="标签" multiple :max-tag-count="1">
                                    <Option v-for="(value,key) in expClassifyTag" :value="value.dictname" :key="key">{{value.dictname}}</Option>
                                </Select>
                                <Icon type="md-add" size="17" color="#a8a6c8"  @click="addLabelsModal = true"  class="add_icon"/>
                                <Tag closable v-for="(item,index) in mergeLabels" :key="index" @on-close="handleCloseTag(item)" :title="item" class="flex width_150">
                                {{ item }}
                                </Tag>
                  </FormItem>
                    <FormItem label="难度" prop="difficulty">
                        <RadioGroup v-model="formValidate.difficulty">
                            <Radio label="Simple">简单</Radio>
                            <Radio label="Medium">中等</Radio>
                            <Radio label="Hard">较难</Radio>
                        </RadioGroup>
                    </FormItem>
                    <FormItem label="可见范围" prop="isPublic">
                        <RadioGroup v-model="formValidate.isPublic" @on-change="changePublic">
                            <Radio label="1">单位</Radio>
                            <Radio label="0">个人</Radio>
                        </RadioGroup>
                        <span v-if="!isCreate" style="color:#f90;position:absolute;white-space: nowrap;"> <Icon type="ios-information-circle-outline" />可见范围由个人修改为单位时，课程使用的个人资源(课件、图片)的可见范围将变为单位</span>
                    </FormItem>
                    <FormItem label="是否自学" prop="selfType">
                        <RadioGroup v-model="formValidate.selfType">
                            <Radio :label="0" :disabled="hasSelfExperiment">否</Radio>
                            <Radio :label="1" :disabled="hasNotSelfExperiment">是</Radio>
                        </RadioGroup>
                         <span v-if="!isCreate" style="color:#f90;position:absolute;white-space: nowrap;">
                             <Icon type="ios-information-circle-outline" />
                                是否自学修改时，需要清空已选课件
                        </span>
                    </FormItem>
                    <FormItem label="课件" prop="expDtoList" class="template-lable">
                        <Button type="primary" ghost @click="refreshExp('','','btn')" v-if="flagOldExp">选择</Button> 
                        <!-- <span style="color:#f90;maigin-left:10px;">请先选择课程类型</span> |  -->
                        <span>课件总数：<Tag color="var(--url-color)">{{selectExpers.length}}</Tag></span>
                        <div style="width:800px;margin: 10px 0px;" class="selectExpers_table" v-if="flagOldExp">
	                        <!-- <div class="chose-wrap" v-for="exper in selectExpers" :key="exper.ecid" style="display:inline-block;margin-right:10px;">
	                            <span style="margin-right:5px;">{{exper.ecname}}</span>
	                            <img src="../../assets/globalIcon/dis-del.png" style="width: 13px;height: auto;margin-legcursor: pointer;vertical-align:text-top;" @click="delSelExper(exper.ecid)">
	                        </div> -->
                            <Table :data="selectExpers" :columns="selectExpersCol" border ref="selectExpersIndex">
                            <template slot="action" slot-scope="{ row, index }">
                                <Tooltip
                                    content="下移"
                                    placement="left"
                                    @click.native="downSelectExpers(index)"
                                >
                                    <Icon type="md-arrow-down" size="20" v-if="selectExpers.length != index + 1"/>
                                </Tooltip>
                                <Tooltip
                                    content="上移"
                                    placement="left"
                                    @click.native="upSelectExpers(index)"
                                >
                                    <Icon type="md-arrow-up" size="20" v-if="index != 0"/>
                                </Tooltip>
                                <Poptip
                                    confirm
                                    transfer
                                    title="确定要删除吗？"
                                    @on-ok="delSelExper(row.ecid)"
                                >
                                    <Icon type="ios-close-circle-outline" size="20"/>
                                </Poptip>
                            </template>
                            </Table>
                        </div>

                        <!-- 折叠板 -->
                        <div style="width:800px;margin: 10px 0px;" v-if="!flagOldExp">
                            <collapseExp ref="collapseForm" 
                            :collapseArr="collapse"
                            @changeAddFrom="changeAddFrom" 
                            @refreshExp="refreshExp('','','btn')" 
                            @changeCollapse="changeCollapse"
                            @delSelExper="delSelExper"
                            @sumExpList="sumExpList"
                            />
                        </div>
                       
                    </FormItem>
                  
                  
                  
                     <FormItem label="课时" prop="hours">
                        <InputNumber :min="1"  :step="1" :max="999" v-model="formValidate.hours" disabled></InputNumber>
                    </FormItem>
                    <FormItem label="封面图片" prop="courseLogo" v-show="showImgItem">
                        <Button type="primary" ghost @click="searchFileName='';searchFilePublic='';videoPage=1;getVideoList('Covertitle')">选择</Button>
                        <div class="chose-wrap" v-show="formValidate.topology != ''&& useImagePath != ''">
                            <div style="display: flex;justify-content: flex-start;align-items: center">
                                <!--<img src="../../assets/exper/guide.png" class="chose-s2-icon">-->
                                <div class="chose-name">
                                	<img :src="handleImage(useImagePath)" style="display:inline-block;height:40px;width:auto;vertical-align: middle;">
                                </div>
                            </div>
                            <img src="../../assets/globalIcon/dis-del.png" style="width: 13px;height: 14px;cursor: pointer" @click="clearImg">
                        </div>
                    </FormItem>
                    <FormItem label="描述" prop="description">
                        <Input v-model.trim="formValidate.description" type="textarea" :maxlength="200" :autosize="{minRows: 2,maxRows: 5}" placeholder="描述"></Input>
                    </FormItem>
                    <FormItem>
                        <Button type="primary" @click="saveCourse('formValidate')" :loading="creatExperLoading">确定</Button>
                        <Button @click="handleReset('formValidate')" style="margin-left: 8px">重置</Button>
                    </FormItem>
                </Form>
            </div>
        </div>
        <!--工程模板-->
            <DrawerPage 
                v-model="addExperModel"
                select
                title="课件"
                :columns="expCol" 
                :data="experData" 
                :loading="experLoading"
                :total=experTotalCount 
                :size.sync="experCurSize" 
                :page.sync="experCurPage"
                showSelectTag
                selectName="ecname"
                selectKey="ecid"
                :disabled="(data) => getResourceDisStatus(data.isPublic === '0',data.createUserId) || addIds.includes(data.ecid)"
                :selection.sync="flagOldExp ? selectExpers : collapse[firstIndex].courseexpchapterDtoList[secondIndex].expOutDtoList"
                @queryFun="getExpListNotPrivates">
                <!-- <ResourseUsageIllustrate type="课程" slot="rule"></ResourseUsageIllustrate> -->
                <template slot="search">
                    <Cascader :data="typeExpArr" v-model="typeCodeArr" @on-change='changeTypeExpArr' style="width: 150px;" placeholder="请选择方向类型" ></Cascader>
                        <i-select clearable v-model="selectDifficult" placeholder="难度" style="width: 150px;" @on-change="experOnChange(1)">
                            <i-option value="Simple">简单</i-option>
                            <i-option value="Medium">中等</i-option>
                            <i-option value="Hard">较难</i-option>
                        </i-select>
                        <i-select clearable v-model="selectVisibility" placeholder="可见范围" style="width: 150px;" @on-change="experOnChange(1)">
                            <i-option value="2">系统</i-option>
                            <i-option value="1">单位</i-option>
                            <!-- <i-option value="0">个人</i-option> -->
                        </i-select>
                        <Select filterable clearable v-model="labelList" placeholder="标签" style="width: 150px;" @on-change="experOnChange(1)" multiple :max-tag-count="1">
                        <Option v-for="(value,key) in expClassifyTag" :value="value.dictname" :key="key">{{value.dictname}}</Option>
                        </Select>
                        <Input v-model.trim="expName" placeholder="课件名称" clearable @on-change="experOnChange(1)" style="width: 150px;"/>
                        <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshExp('','','refresh')"><i class="el-icon-refresh-right" /></Button>
                </template>
            </DrawerPage>
            <!-- <div style="display: flex;justify-content: space-between;margin-top: 20px">
                <div style="margin-left: 15px;font-size: 14px;font-weight: bold;width: 60px;margin-top: 6px">课件</div>
                <div style="display: flex;justify-content: space-between;"> -->
					<!-- <Select filterable v-model="direction" placeholder="方向" @on-change="changeDirection" style="width: 150px;margin:0px 15px 10px 0px;" clearable>
						<Option v-for="(value,key) in expClassifyLevel1" :value="value.dictid" :key="key">{{value.dictname}}</Option>
					</Select>
					<Select filterable v-model="typeCode" placeholder="类型" @on-change="changeTypeCode" style="width: 150px;margin:0px 15px 10px 0px;" clearable>
						<Option v-for="(value,key) in expClassifyLevel2" :value="value.dictid" :key="key">{{value.dictname}}</Option>
					</Select> -->
                    <!-- <Cascader :data="typeExpArr" v-model="typeCodeArr" @on-change='changeTypeExpArr' style="width: 150px;margin:0px 15px 10px 0px;" placeholder="请选择方向类型" ></Cascader>
                    <i-select clearable v-model="selectDifficult" placeholder="难度" style="width: 150px;margin:0px 15px 10px 0px;" @on-change="experOnChange(1)">
                        <i-option value="Simple">简单</i-option>
                        <i-option value="Medium">中等</i-option>
                        <i-option value="Hard">较难</i-option>
                    </i-select>
                	<i-select clearable v-model="selectVisibility" placeholder="可见范围" style="width: 150px;margin:0px 15px 10px 0px;" @on-change="experOnChange(1)">
                        <i-option value="2">系统</i-option>
						<i-option value="1">单位</i-option>
						<i-option value="0">个人</i-option>
                    </i-select>
                	<Select filterable clearable v-model="labelList" placeholder="标签" style="width: 150px;margin:0px 15px 10px 0px;" @on-change="experOnChange(1)" multiple :max-tag-count="1">
                    <Option v-for="(value,key) in expClassifyTag" :value="value.dictname" :key="key">{{value.dictname}}</Option>
                    </Select>
                    <Input v-model.trim="expName" placeholder="课件名称" clearable @on-change="experOnChange(1)" style="width: 150px;"/>
                    <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshExp()"><i class="el-icon-refresh-right" /></Button>

                </div>
            </div> -->
            <!-- <Divider />
            <div style="max-height:calc(100vh - 260px);overflow: hidden auto;">
            	<div v-if="selectExpers.length === 0 && flagOldExp">
	            	<p>已选课件总数：<Tag color="purple">{{selectExpers.length }}</Tag></p>
	            </div>
                <div v-else-if="flagOldExp">
	            	<p>已选课件总数：<Tag color="purple">{{selectExpers.length}}</Tag></p>
	            	<Tag color="default" v-for="exper in selectExpers" :key="exper.ecid" closable @on-close="handleExperClose(exper.ecid)">{{exper.ecname}}</Tag>
	            </div>
                <div v-else-if="collapse[firstIndex].courseexpchapterDtoList[secondIndex].expOutDtoList.length === 0 && !flagOldExp">
	            	<p>已选课件总数：<Tag color="purple">0</Tag></p>
	            </div>
            	<div v-else>
	            	<p>已选课件总数：<Tag color="purple">{{collapse[firstIndex].courseexpchapterDtoList[secondIndex].expOutDtoList.length}}</Tag></p>
	            	<Tag color="default" v-for="exper in collapse[firstIndex].courseexpchapterDtoList[secondIndex].expOutDtoList" :key="exper.ecid" closable @on-close="handleExperClose(exper.ecid)">{{exper.ecname}}</Tag>
	            </div>
	            <Divider />
                <Table border ref="experTable" :columns="expCol" :data="experData" :loading="experLoading"
                	@on-select-all="selectExper" @on-select="selectExper"
                   	@on-select-all-cancel="removeExper" @on-select-cancel="removeExper"></Table>
            </div>
            <div style="display: flex;justify-content: center;margin: 15px 0">
                <Page :total=experTotalCount :page-size="experCurSize" :current="experCurPage" show-total show-elevator @on-change="experOnChange"/>
            </div> -->
        <!-- </Drawer> -->
        <!--图片列表-->
        <DrawerPage 
            v-model="imgModal"
            select
            title="封面图片"
            :columns="videoCol" 
            :data="videoList" 
            :loading="fileListLoading"
            :total='videoTotal' 
            :size.sync="videoPageSize" 
            :page.sync="videoPage"
            @queryFun="getVideoList"
        >
            <ResourseUsageIllustrate type="课程" slot="rule"></ResourseUsageIllustrate>
            <template slot="search">
                <i-select clearable v-model="searchFilePublic" placeholder="可见范围" style="width: 150px;margin-left: 15px" @on-change="searchFile">
                    <i-option value="range">平台</i-option>
                    <i-option value="system">系统</i-option>
                    <i-option value="company">单位</i-option><i-option value="person">个人</i-option>
                </i-select>
                <Input v-model.trim="searchFileName" placeholder="图片名称" style="width: 180px;" clearable @on-change="searchFile"/>
                <Button class="header-btn" type="primary" ghost style="height: 32px;margin-left: 5px;" @click="refreshImg()"><i class="el-icon-refresh-right" /></Button>
            </template>
        </DrawerPage>
  <!-- 添加标签 -->
		<Modal
        v-model="addLabelsModal"
        title="添加标签">
        <Input v-model.trim="addLabels" placeholder="请输入标签" :maxlength="64" style="width: 95%;"/>
         <WarningTip content="请输入个数为1-64的字符"></WarningTip>
         <div slot="footer">
            <Button @click="cancelLabels" type="text">取消</Button>
            <Button @click="submitLabels" type="primary" :disabled="!addLabels">确定</Button>
        </div>
    </Modal>
    </div>
</template>
<script>
    import {getIconData} from '@/api/icon.js'
    import $ from 'jquery'
    import encryption from '@/libs/encryption.js'
    import {experType,getSelLabelType,dictEntrysSave,dictEntrysSaveBatch} from '@/api/dict.js'
    import {submitExper,modifyExper,experimentDetail} from '@/api/selfStudy/courseExp.js'
    import defaultImg from '@/assets/globalIcon/course.jpg'
    import {getFilesData} from '@/api/uploadFile.js'
    import { validateName,validateName128 } from '@/libs/reg'
    import {
		getcourselist,
		delCourse,
		addCourse,
		updateCourse,
        getExpListNotPrivate,
		courseDetail,
        addOrUpdateChapter,
        getChapter
	} from '@/api/selfStudy/courseExp.js'
	import ResourseUsageIllustrate from '@/components/resourse-usage-illustrate'
    import collapseExp from './collapseExp.vue'
    import {typeAndDirectionMixin} from '@/mixin/study.js'
    // import { collapseData } from './mixinCollapse';
    export default {
    	name:'CreateCourse',
        components:{ResourseUsageIllustrate,collapseExp},
        mixins:[typeAndDirectionMixin,/*collapseData*/],
        data () {
            const validateMinram = (rule,value,callback) => {
                let val = parseInt(value)
                if(val > 0 && val <= 999){
                    callback()
                }else {
                    callback(new Error('请输入时长为1——999'))
                }
            }
            const directionValidator = (rule,value,callback)=>{
                if(!this.formValidate.direction){
                    callback(new Error('方向不能为空'));
                }else{
                     callback()
                }
               
            }
            const expDtoListValidator = (rule,value,callback)=>{
                if(!this.formValidate.expDtoList.length){
                    callback(new Error('请至少选择一个课件'));
                }else{
                     callback()
                }
            }
            let userInfo  = sessionStorage.getItem('November')
	        userInfo  = JSON.parse(encryption.SelfUseDecrypt(userInfo))
            return {
                hasSelfExperiment: false,
                hasNotSelfExperiment: false,
                // 用户信息
                userName: '',
                USER_ID: '',
                // 页面设置
                defaultImg,
                fullHeight: document.documentElement.clientHeight,
                fullWidth: document.documentElement.clientWidth,
                contentHei: 'auto',
                upLoadIconUrl: `${this.baseURL}/virtual/icon/fileUpload`,
                // 先判断状态
                isCreate: true,
                receiveData: {},
                showImgItem: true,
                ecid: '',
                // 页面标题
                titleText: '',
                // 表单
                formValidate: {
                    "selfType": 0,
                    "designer": userInfo.nickname,
                    "ccname": "", //课程名称
                    "courseLogo": "", //课程logo
                    "credit": 0, //学分
                    "description": "", //描述
                    "difficulty": "Simple", //难度
                    "enable": 1, //是否可用
                    "expDtoList": [], //课件列表
                    "filePath": "", //logo路径
                    "hours": 0, //用时
                    "isPublic": "1", //可见范围
                    "typeCode": "", //类型
                    // "direction":"",
                    labels: [],
                },
                ruleValidate: {
                    ccname: [
                        { required: true, max: 128, message: '课程名称长度为1—128个字符', trigger: 'change' },
                        { validator: validateName128, trigger: 'change' }
                    ],
                    // labels: [
                    //     { required: true,  type:'array',min:1,message: '标签不能为空', trigger: 'change' }
                    // ],
                    typeCode: [
                        { required: true, message: '类型不能为空', trigger: 'change' }
                    ],
                    direction: [
                         { required: true, message: '方向不能为空', trigger: 'change' },
                         {validator:directionValidator}
                    ],
                    // hours: [
                    //     { required: true, validator: validateMinram, trigger: 'change' },
                    // ],
                    difficulty: [
                        { required: true, message: '难度不能为空', trigger: 'change' }
                    ],
                    isPublic: [
                        { required: true, message: '可见范围不能为空', trigger: 'change' }
                    ],
                    selfType: [
                        { required: true, message: '是否自学不能为空', type: 'number', trigger: 'change' }
                    ],
                    expDtoList: [
                        { required: true, type: 'array', min: 1, message: '请至少选择一个课件', trigger: 'change' },
                        { validator: expDtoListValidator }
                    ],
                    // envtempid: [
                    //     { required: true, validator: validateTemId, trigger: 'change' }
                    // ],
                    // guide: [
                    //     { required: true, message: 'The guide cannot be empty', trigger: 'change' }
                    // ],
                    desc: [
                        { max: 200, message: 'The desc cannot exceed 200 letters', trigger: 'change' },
                    ],
                },
                creatExperLoading: false,
                useImagePath: '',
                // 课件分类
                expClassify: [],
                expClassifyLevel1: [],
                expClassifyLevel2: [],
                // 课件
                addExperModel: false,
                experCurPage: 1,
                experCurSize: 10,
                experTotalCount: 0,
                experData: [],
                expName: '',
                diffculty: '',
                coursecExpcontentList: [],
                selectExpers: [],
                // 课件table
                expCol: [
                    {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    //				    {
                    //						type: 'index',
                    //						width: 60,
                    //						align: 'center',
                    //						ellipsis: true,
                    //						tooltip:true
                    //					},
                    {
                        title: '名称',
                        key: 'ecname',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                        title: '设计者',
                        key: 'designer',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                      title: '方向',
                      // key: 'typeCode',
                      align: 'center',
                      ellipsis: true,
                      tooltip:true,
                      render:(h,params)=> {
                        let text = this.handleDirection(params.row.typeCode)
                        return h('div',text)
                      },
                    },
                    {
                      title: '类型',
                      key: 'typeCode',
                      align: 'center',
                      ellipsis: true,
                      tooltip:true,
                      filter:(typeCode)=>{
                        return this.handleCodeType(typeCode)
                      }
                    },
                    {
                        title: '难度',
                        key: 'difficulty',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true,
                        minWidth:60,
                    },
                    {
                        title: '课件类型',
                        key: 'expType',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true,
                        minWidth:90,
                        render: (h, params) => {
                            return h('span', this.handleExpType(params.row.expType))
                        }
                    },
                    {
                        title: '可见范围',
                        key: 'isPublic',
                        width: 100,
                        align: 'center',
                        minWidth:80,
                        render: (h, params) => {
                            return h('div', {
                                style: {
                                    color: this.handlePublic(params.row.isPublic).color
                                }
                            }, this.handlePublic(params.row.isPublic).text)
                        }
                    },
                    {
                        title: '课件用途',
                        key: 'selfType',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true,
                        minWidth:80,
                        render: (h, params) => {
                            let selfType = params.row.selfType
                            return h('div', {}, this.selftypeMap[selfType])
                        }
                    },
                    {
                        title: '课时',
                        key: 'hours',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true,
                        minWidth:60,
                    },
                    {
                        title: '标签',
                        key: 'labels',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true,
                        render: (h, params) => {
                            if (params.row.labels != 'null') {
                                return h('Tooltip', {
                                    props: {
                                        'max-width': '300',
                                        transfer: true,
                                        content: params.row.labels
                                    },
                                    style: {
                                        width: '100%',
                                    }
                                }, [
                                    h('p', {
                                        style: {
                                            overflow: 'hidden',
                                            'text-overflow': 'ellipsis'
                                        }
                                    }, params.row.labels)
                                ])
                            } else {
                                return h('span', '-')
                            }
                        }
                    },
                    {
                        title: '描述',
                        key: 'description',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    //					{
                    //                      title:'操作',
                    //                      key:'action',
                    //                      align:'left',
                    //                      width:120,
                    //                      render:(h,params)=>{
                    //                          let text = ''
                    //                          if(params.row._checked){
                    //                              text = '添加'
                    //                          }else {
                    //                              text = '添加'
                    //                          }
                    //                          return h('a',{
                    //                              style: {
                    //                                  'display': 'flex',
                    //                                  'justify-content': 'flex-start',
                    //                                  'align-items': 'center',
                    //                                  color:params.row._checked?'#2f70ff':'grey'
                    //                              },
                    //                          },[
                    //                              h('div', {
                    //                                  on: {
                    //                                      'click': ()=>{
                    //                                          this.chooseExper(params)
                    //                                      },
                    //                                  },
                    //                                  style:{
                    //                                      'margin-left':'15px',
                    //                                  }
                    //                              }, [
                    //                                  h('img', {
                    //                                      attrs: {
                    //                                          src: params.row._checked?require('../../assets/globalIcon/choosed.png'):require('../../assets/globalIcon/add.png'),
                    //                                      },
                    //                                      style: {
                    //                                          cursor: 'pointer',
                    //                                          'margin-right':'5px',
                    //                                          'vertical-align': 'middle',
                    //                                          width:'16px',
                    //                                          height:'16px',
                    //                                          display:'inline-block',
                    //                                      },
                    //                                  }),
                    //                                  h('span',{
                    //                                      style: {
                    //                                          cursor: 'pointer',
                    //                                      },
                    //                                  },text)
                    //                              ])
                    //                          ])
                    //                      }
                    //                  },
                ],
                selftypeMap:{
                  0:'培训',
                  1:'自学',
                  2:'通用',
                },
                searchTemplateName: '',
                experLoading: false,
                searchTemNameInput: '',
                selectProTemModel: 'designer',
                templateVisibility: 'designer',
                setUserTableHei: '700',
                selectDifficult: '',
                direction: '',
                typeCode: '',
                selectVisibility: '',
                labelList: [],
                // 图片
                imgModal: false,
                videoPage: 1,
                videoPageSize: 14,
                videoList: [],
                videoTotal: 0,
                videoCol: [
                    {
                        title: '名称',
                        key: 'originName',
                        align: 'center',
                        // render:(h,params)=>{
                        //     let fileName = params.row.fileName
                        //     fileName = fileName.split('.')[0]
                        //     return h('div',fileName)
                        // }
                    },
                    {
                        title: '缩略图',
                        key: 'path',
                        align: 'center',
                        render: (h, params) => {
                            return h('img', {
                                attrs: {
                                    src: this.handleImage(params.row.path)
                                },
                                style: {
                                    display: 'inline-block',
                                    maxHeight: '40px',
                                    width: 'auto',
                                    verticalAlign: 'middle'
                                }
                            })
                        }
                    },
                    // {
                    //     title: 'ID',
                    //     key: 'id',
                    //     align: 'center',
                    // },
                    //                  {
                    //                      title:'类型',
                    //                      key:'bucket',
                    //                      align:'center',
                    //                      width:80,
                    //                  },
                    {
                        title: '可见范围',
                        key: 'visibility',
                        width: 100,
                        align: 'center',
                        render: (h, params) => {
                            return h('div', {
                                style: {
                                    color: this.handlePublic(params.row.visibility).color
                                }
                            }, this.handlePublic(params.row.visibility).text)
                        }
                    },
                    {
                        title: '内容',
                        key: 'check',
                        align: 'center',
                        width: 100,
                        render: (h, params) => {
                            return h('div', [
                                h('a', {
                                    on: {
                                        click: () => {
                                            this.checkInfo(params);
                                        }
                                    }
                                }, '查看')
                            ]);
                        }
                    },
                    {
                        title: '创建者',
                        key: 'creatorName',
                        align: 'center',
                    },
                    {
                        title: '创建时间',
                        key: 'created',
                        align: 'center',
                    },
                    {
                        title: '操作',
                        key: 'action',
                        width: 100,
                        align: 'center',
                        render: (h, params) => {
                            let text = ''
                            if (params.row.imgUseFlag) {
                                text = '已用'
                            } else {
                                text = '使用'
                            }
                            let status = this.getResourceDisStatus(params.row.visibility === 'privete', params.row.creator);
                            return h('a', {
                                style: {
                                    //                                  'display': 'flex',
                                    //                                  'justify-content': 'flex-start',
                                    //                                  'align-items': 'center',
                                    color: params.row.imgUseFlag ? '#2f70ff' : 'grey',
                                    cursor: status ? 'not-allowed' : 'pointer'
                                },
                            }, [
                                h('div', {
                                    on: {
                                        'click': () => {
                                            if (status) {
                                                //this.$Message.warning('单位的课程不允许选择个人资源');
                                                return;
                                            }
                                            this.chooseImg(params)
                                        },
                                    },
                                    style: {
                                        //                                      'margin-left':'15px',
                                    }
                                }, [
                                    h('img', {
                                        attrs: {
                                            src: params.row.imgUseFlag ? require('../../assets/globalIcon/choosed.png') : require('../../assets/globalIcon/add.png'),
                                        },
                                        style: {
                                            'margin-right': '5px',
                                            'vertical-align': 'middle',
                                            width: '16px',
                                            height: '16px',
                                            display: 'inline-block',
                                        },
                                    }),
                                    h('span', {}, text)
                                ])
                            ])
                        }
                    },
                ],
                fileListLoading: false,
                searchFileName: '',
                searchFilePublic: '',
                // 获取标签
                expClassifyTag: [],
                selectExpersCol: [
                    {
                        title:'序号',
                        type: 'index',
                        align: 'center',
                        width: 60,
                    },
                    // {
                    //     title: '课件课程序号',
                    //     key:'orderNo',
                    //     align: 'center',
                    //     width: 120,
                    // },
                    {
                        title: '课件名称',
                        key: 'ecname',
                        align: 'center',
                        ellipsis: true,
                        tooltip: true
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 150,
                        align: 'center',
                    },
                ],
                addLabelsModal: false,
                addLabels: '',
                addLabelsArr: [],
                mergeLabels: [],
                courseClassifyName: [],
                // 折叠数据
                collapse: [
                    {
                        name: '第1章',
                        courseexpchapterDtoList: [
                            {
                                name: '第1节',
                                orderby:0,
                                expOutDtoList: []
                            }
                        ]
                    },
                ],
                firstIndex: 0,
                secondIndex: 0,
                getChapterCcid:'',
                getChapterID: '',
                flagOldExp:false,
                typeExpArr :[],
                typeCodeArr :[],
                addIds:[]
            }
        },
        computed:{
        	isOwn:function(){
        		return this.USER_ID == this.formValidate.createUserID || this.isCreate 
            },
            pageTitle () {
                //当前菜单显示名
                return this.$route.meta.title;
            },
        },
        created(){
            // 获取用户id
            let November = sessionStorage.getItem('November')
            November = JSON.parse(encryption.SelfUseDecrypt(November))
            this.USER_ID = November.userId
            this.userName = November.userName
        },
        filters:{
        	difficultyFilter(val) {
				let difficultyStr = '';
				val = val.toLowerCase()
				switch (val) {
					case 'simple':
						difficultyStr = '简单';
						break;
					case 'commonly':
						difficultyStr = '一般';
						break;
					case 'medium':
						difficultyStr = '中等';
						break;
					case 'hard':
						difficultyStr = '较难';
						break;
				}
				return difficultyStr;
			},
        },
        mounted(){
        	this.classification().then(data => {
        		// 是新增还是修改
	            if(this.$route.query.action === 'create'){
	                this.isCreate = true
	                this.titleText = '新增课程'
                    this.showImgItem = true
	            }else if(this.$route.query.action === 'modify'){
	                this.isCreate = false
	                this.titleText = '修改课程'
	                this.showImgItem = true
	                this.ccid = this.$route.query.ccid
	                // 获取课件详情
                    this.getChapter()
	                this.getCourseDetail();
	            }
                this.addBreadItem({ name: this.titleText });
        	})
            // this.setStyle()
            this.getSelLabelType()
            // window.onresize = () => {
            //     this.setStyle()
            // }

        },
        watch: {
            selectExpers (list) {
                this.hasNotSelfExperiment = list.some(item => item.selfType === undefined || item.selfType === 0)
                this.hasSelfExperiment = list.some(item => item.selfType === 1)
                this.formValidate.hours = list.reduce((prev, next) => prev + next.hours, 0);
            },
            'formValidate.labels': {
			handler (val) {
				this.mergeLabels = [...new Set(this.formValidate.labels.concat(this.addLabelsArr))]
			},
			deep:true
		},
		addLabelsArr: {
			handler (val) {
				this.mergeLabels = [...new Set(this.formValidate.labels.concat(this.addLabelsArr))]
			},
			deep: true,
			immediate:true,
		},
		mergeLabels: {
			handler (val) {

			},deep:true
		}
        },
        beforeRouteLeave (to, from, next) {
            if(to.path === '/course'){
                //to.query.page = this.$route.query.page
                next()
            }else {
            	sessionStorage.removeItem("queryObj");
                next()
            }
        },
        methods:{
            changeAddFrom (collapse) {
                console.log('===this',collapse);
            },
            sumExpList (val) {
                this.formValidate.expDtoList = val
                this.selectExpers = val
            },
            changeCollapse (collapse) {
            this.collapse = collapse    
            console.log('changeCollapse ~ this.collapse', this.collapse)
            },
            //下移
            downSelectExpers(index) {
            if (index == this.selectExpers.length - 1) return;
            let arr = this.selectExpers;
                arr[index] = arr.splice(index + 1, 1, arr[index])[0]
            this.selectExpers = arr
            },
            //上移
         upSelectExpers(index) {
            if (index == 0) return;
            let arr = this.selectExpers;
            arr[index] = arr.splice(index - 1, 1, arr[index])[0]
            this.selectExpers = arr
        },
        // 
            submitLabels () {
                if (this.addLabels == '') {
                    this.addLabels = ''
                    return
                }
                if (this.courseClassifyName.includes(this.addLabels) || this.mergeLabels.includes(this.addLabels) || this.addLabelsArr.includes(this.addLabels)) {
                    this.$Message.warning({
                        content: `输入值${this.addLabels}重复数据，请重新输入！`,
                        duration: 3
                    })
                    // this.addLabels = ''
                } else {
                    this.addLabelsArr.push(this.addLabels)
                    this.addLabels = ''
                    this.addLabelsModal = false
                }
            },
        cancelLabels () {
			this.addLabels = ''
			this.addLabelsModal = false
        },
        handleCloseTag (item) { // 合拼数组问题，要对应处理对应的数组
			// let index = this.mergeLabels.indexOf(item)
			let addLabelsIndex = this.addLabelsArr.indexOf(item)
			let formIndex = this.formValidate.labels.indexOf(item)
			if (formIndex > -1) {
				this.formValidate.labels.splice(formIndex,1)
			}
			if (addLabelsIndex > -1) {
				this.addLabelsArr.splice(addLabelsIndex,1)
			}
            },
        // 保存标签
		dictEntrysSave () {
			let name = this.addLabelsArr[0]
			if (this.addLabelsArr.length == 1) { // 单个数据保存
				let res = dictEntrysSave(name)
				console.log('dictEntrysSave ~ res', res)
			} else {
				let result = dictEntrysSaveBatch(this.addLabelsArr)
				console.log('dictEntrysSave ~ result', result)
			}
        },
            // 设置高度
            setStyle(){
                window.fullHeight = document.documentElement.clientHeight;
                window.fullWidth = document.documentElement.clientWidth;
                this.fullHeight = window.fullHeight;
                this.fullWidth = window.fullWidth;
                this.contentHei =   this.fullHeight - 60 - 21 +'px'  // 80是头部高度  60是上下padding
                this.setUserTableHei = this.fullHeight - 212
                this.experCurSize = Math.floor(this.setUserTableHei/50) - 1
                this.videoPageSize = Math.floor(this.setUserTableHei/50) - 1
            },
            // 返回课程列表
            returnCourse(){
                this.$router.push({
                    name: 'course',
                    query:{
                        page:this.$route.query.page
                    }
                })
            },
            changeTypeExpArr (val) {
                console.log('🚀 changeTypeExpArr ~ val:', val)
                if (val.length > 0) {
                    this.typeCode = val[1]
                } else {
                    this.typeCode = ''
                }
                console.log('================',this.typeCode);
                this.experOnChange(1)
            },
            // 获取场景分类
            classification(){
            	return new Promise((resolve,reject) => {
                experType()
                    .then((data)=>{
                        if(data.code == 1){
                            let attribute = data.attribute;
                            this.expClassify = attribute.attribute[0].dictEntryList;
                            this.expClassifyLevel1 = attribute.attribute[0].dictEntryList.filter(dict => !dict.parentid);
							this.expClassifyLevel2 = attribute.attribute[0].dictEntryList.filter(dict => dict.parentid);


						let direct = attribute.attribute[0].dictEntryList;
						let treeExpClassify = {};
						direct.forEach(dict => {
                            if (dict.parentid) { //二级
                                if (!treeExpClassify[dict.parentid]) return;
                                treeExpClassify[dict.parentid].children.push({
                                    value: dict.dictid,
                                    label: dict.dictname
                                })
                            } else if (!treeExpClassify[dict.dictid] && !dict.parentid) { //一级
                                treeExpClassify[dict.dictid] = {
                                    value: dict.dictid,
                                    label: dict.dictname,
                                    children: []
                                }
                            }
                        })
                        this.typeExpArr = Object.values(treeExpClassify)
						// console.log('=========================treeExpClassify========',Object.values(treeExpClassify));

                            resolve(attribute)
                        }else{
                        	resolve();
                        }
                    })
                    .catch((err)=>{
                    	resolve();
                    });
               })
            },
            //获取课程详情
            getCourseDetail(){
            	courseDetail(this.ccid).then(data => {
					if (data.code == 1) {
						this.coursecExpcontentList = data.data.coursecExpcontentList;
						this.selectExpers = data.data.coursecExpcontentList;
						this.formValidate = data.data.coursecontent;
                        this.formValidate.typeCode = this.$route.query.typeCode;
						let direction1 = this.getDirection(this.formValidate.typeCode);
						this.expClassifyLevel2 = this.expClassify.filter(dict => dict.parentid == direction1);
						this.formValidate.direction = direction1;
                        this.formValidate.abc = direction1;
						this.formValidate.expDtoList = data.data.coursecExpcontentList;
                        this.useImagePath = data.data.coursecontent.courseLogo;
                        this.selectExpers.forEach(item => {
                            if (item.ccid) {
                                item.typeCode = this.getTypeCodeName(this.typeCode)
                            }
                        })
                        if (data.data.coursecontent.labels) {
                            let result = this.getLabelsSet(this.expClassifyTag, data.data.coursecontent.labels.split(';'))
								this.formValidate.labels = result.select
								// this.addLabelsArr = result.input
                        }
                        this.selectExpers.sort((a, b) => { return a.orderNo - b.orderNo })
					} else {
						this.$Message.error(data.message)
					}
				}).catch(error => {})
            },
            getChapter () {
                getChapter(this.ccid).then(res => {
                    if (res.code == 1) {
                        if (res.data.name == '该课程未绑定章节') {
                            this.flagOldExp = true
                        } else {
                            if (res.data) {
                                this.flagOldExp = false
                                let resList = res.data.courseexpchapterDtoList
                                resList.sort((a, b) => { return a.orderby - b.orderby })
                                resList.forEach(item => {
                                    item.courseexpchapterDtoList.forEach((item2) => { //orderno
                                        item2.expOutDtoList = this.expSort(item2.expOutDtoList, 'orderNo')
                                    })
                                    item.courseexpchapterDtoList = this.expSort(item.courseexpchapterDtoList, 'orderby')
                                })
                                console.log('🚀 ~ file: createCourse.vue:1002 ~ getChapter ~ resList', resList)
                                this.collapse = resList
                                this.getChapterCcid = res.data.ccid
                                this.getChapterID = res.data.id
                            } else {
                                this.$Message.warning(res.message + '，先启用课程')
                            }
                        }
                    }
                }).catch(error => {
                    // this.$Message.warning('获取课件数据失败')
                })
            },
            expSort (list,type) { // 排序
                if (type == 'orderby') {  
                    return list.sort((a, b) => { return a.orderby - b.orderby })
                } else {
                    return list.sort((a, b) => { return a.orderNo - b.orderNo })
                }
            },


            getLabelsSet (data1, data2) {
			let result = {
				select: [],
				input: []
			}
			data2.forEach(item2 => {
				data1.forEach(item => {
					if (item2 !== item.dictname) {
						result.input.push(item2)
					} else {
						result.select.push(item2)
					}
				})
			})
			result.input =[ ...new Set(result.input)]
			result.select = [...new Set(result.select)]
			return result;
            },
            getTypeCodeName (typeCode) {
                let dictid = ''
                this.expClassifyLevel2.forEach(item => {
                    if (item.dictid == typeCode) {
                         dictid = item.dictid
                    }
                })
                return dictid;
            },
            getDirection(type){
				let types = this.expClassify.filter(dict => dict.dictid == type);
				if(types.length > 0){
					let parentTypes = this.expClassify.filter(dict => dict.dictid == types[0].parentid);
					return parentTypes.length > 0 ? parentTypes[0].dictid : ''
				}else{
					return ''
				}
			},
            // 选择课件
			getExpListNotPrivates() {
				// if(!this.formValidate.typeCode){
				// 	this.$Message.warning('请先选择课程方向和类型');
				// 	return;
                // }
				this.addExperModel = true
				this.experLoading = true
				let params = {
					"pageIndex": this.experCurPage,
					"pageSize": this.experCurSize,
					"ecname":this.expName,
					"typeCode":this.typeCode,
                   // selfType: this.formValidate.selfType,
          // 0 培训  1 自学  2 通用   课程自学：1+2 ，非自学
          selfTypeList:this.formValidate.selfType?[1,2]:[0,2],
          // order: 'desc',
                    sortBy: 'createTime'
				}
		        if(this.selectDifficult != 'Commonly'){
		              params.difficulty = this.selectDifficult
		        }
		        if(this.selectVisibility){
		        	params.isPublic = this.selectVisibility
		        }
                if (this.labelList.length > 0) {
                    params.labelList = this.labelList
                }

				getExpListNotPrivate(params).then(data => {
					if (data.code == 1) {
						this.experData = data.data.items;
                        this.experTotalCount = data.data.total;
                        let ids = this.selectExpers.map(exp => exp.ecid);
                         let collapseId = []
                        if (this.flagOldExp) {
                            ids = this.selectExpers.map(exp => exp.ecid);
                        } else {
                            // ids = this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.map(exp => exp.ecid);
                             collapseId = this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.map(exp => exp.ecid);
                        }
                        let addIds = ids.filter(item => !collapseId.some(item2=>item2===item)); 
                        this.addIds = addIds
						this.experData.forEach(item => {
							let {
								difficulty
							} = item;
							difficulty = this.$options.filters.difficultyFilter(difficulty)
							Object.assign(item, {
								'difficulty': difficulty,
								'_checked':collapseId.includes(item.ecid),
								'_disabled':this.getResourceDisStatus(item.isPublic === '0',item.createUserId) || addIds.includes(item.ecid),
							})
						})
					}
					this.experLoading = false;
				}).catch(err => {
					this.$Message.error('获取课件列表失败，请稍后再试')
					this.experLoading = false;
				})
			},
			getResourceDisStatus(isPrivate,creator,type){
				let isNotOwn = !(this.USER_ID == this.formValidate.createUserID || this.isCreate); 
				let isNotCommonCreator = this.formValidate.createUserID !== creator;
                return (this.formValidate.isPublic == 1 || (isNotOwn && isNotCommonCreator)) && isPrivate;
			},
      refreshExp (index, index2,type) {
              console.log('sdfsdfsdfsd',index, index2,type)
                if (index || index2) {
                    this.firstIndex = index
                    this.secondIndex = index2
                }
	          this.experCurPage = 1,
	          this.expName = '',
	          this.selectDifficult = 'Commonly',
              this.selectVisibility = '',
              this.labelList = [],
              this.direction =''
              // this.typeCode =''
              // this.typeCodeArr = []
              if(type =='btn'){
                this.typeCode = this.formValidate.typeCode
                this.typeCodeArr = [this.formValidate.direction,this.formValidate.typeCode]
                // this.changeTypeExpArr([this.formValidate.direction,this.formValidate.typeCode])
              }else{
                this.typeCodeArr = []
              }
	          this.getExpListNotPrivates()
      },
      experOnChange (page) {
				this.experCurPage = page;
				this.getExpListNotPrivates();
      },
            // 获取标签
			getSelLabelType () {
				getSelLabelType().then(res => {
					if (res.code == 1) {
                        this.expClassifyTag = res.data[0].dictEntryList
                        if (this.expClassifyTag.length > 0) {
                            this.courseClassifyName = this.expClassifyTag.map(item => {
                                if (item) {
                                    return item.dictname
                                }
                            })
                        }
					} else {
						this.$Message.error('获取标签失败，请刷新重试')
					}
				}).catch(error => {
					this.$Message.error({
						content: error,
						duration: 3,
					})
				})
			},
            closeDistribution(){
                this.addExperModel = false;
            },
            // 选择图片
            getVideoList(type){
                this.imgModal = true
                if(type==='Covertitle'){
                  this.getVideoImage()
		               return
                }
              
              
              
                let params = {
                    pageIndex:this.videoPage,
                    pageSize:this.videoPageSize
                }
                let data = {
                	bucket:'images',
                }
                if($.trim(this.searchFileName) != ''){
                    data.originName = $.trim(this.searchFileName)
                }
                if($.trim(this.searchFilePublic) != ''){
                	data.visibility = $.trim(this.searchFilePublic)
                }
                this.fileListLoading = true
                getFilesData(params,data)
                    .then((res)=>{
                        if(res.data.code == 1){
                            let attribute = res.data.data;
                            let items = attribute.list;
                            this.videoTotal = attribute.total;
                            for(let i=0;i<items.length;i++){
                                items[i].imgUseFlag = false
                                if(items[i].path === this.useImagePath){
                                    items[i].imgUseFlag = true
                                }
                            }
                            this.videoList = items;
                        }
                        this.fileListLoading = false
                    })
                    .catch((err)=>{
                        this.fileListLoading = false
                    })
            },

          getVideoImage(){
            this.imgModal = true
            let params = {
              pageIndex: this.videoPage,
              pageSize: this.videoPageSize,
              self:0
            };
            let data = {
              type:'Covertitle',
              self:0
            };
            if($.trim(this.searchFileName) != ''){
              data.originName = $.trim(this.searchFileName)
            }
            if($.trim(this.searchFilePublic) != ''){
              data.visibility = $.trim(this.searchFilePublic)
            }
            this.fileListLoading = true
            getIconData(data,params)
            .then((res)=>{
              if(res.data.code == 1){
                let attribute = res.data.data;
                let items = attribute.items||[];
                this.videoTotal = attribute.total;
                
                for(let i=0;i<items.length;i++){
                  items[i].originName = items[i].name
                  items[i].path = items[i].path.replace('/files/','')
                  items[i].imgUseFlag = false
                  if(items[i].path === this.useImagePath){
                    items[i].imgUseFlag = true
                  }
                }
                this.videoList = items;
              }
              this.fileListLoading = false
            })
            .catch((err)=>{
              this.fileListLoading = false
            })
          },
          
          
            videoOnChange(val){
                this.videoPage = val;
                this.getVideoList();
            },
            searchFile(val){
                this.videoPage = 1
                this.getVideoList();
            },
            refreshImg(){
                this.videoPage = 1
                this.searchFileName = ''
                this.searchFilePublic = ''
                this.getVideoList()
            },
            closeImgModalBtn(){
                this.imgModal = false
            },
            checkInfo(params){
                let path = params.row.path;
                window.openTrain(`/api/minio/filePreview?path=${path}`);
            },
            chooseImg(params){
                if(params.row.imgUseFlag){
                    this.$Message.info({
                        content:'已使用该图片！',
                        duration:3,
                    })
                }else {
                    let _index = params.row._index
                    for(let i=0;i<this.videoList.length;i++){
                        this.videoList[i].imgUseFlag = false
                    }
                    this.$set(this.videoList[_index],'imgUseFlag',true)
                    this.formValidate.topology = params.row.originName
                    this.useImagePath =  params.row.path
                    //存储图片可见范围
					this.useImageVisibility = params.row.visibility
                }
            },
            // 清空选择的图片
            clearImg(){
                this.formValidate.topology = ''
                this.useImagePath =  ''
            },
            handleImage(logo){
                let src = ''
                if(logo){
                    if(logo.indexOf('Learn') > -1){
                        src = logo
                    }else {
                        src = `/Learn/${logo}`
                    }
                }else {
                    // src = this.defaultImg // 选择封面一瞬间会闪现默认图片
                    src = ''
                }
                return src
            },
            //删除团队
	        handleExperClose(id) {
	        	let index = this.experData.findIndex(item => item.ecid == id);
	        	if(index!=-1){
	        		this.$refs.experTable.toggleSelect(index);
	        	}else{
	        		this.delSelExper(id);
	        	}
	        },
            selectExper (selection, row) {  
                // let flag = false
                // if (this.selectExpers.length > 0) { // 判断是否同一code
                //     if (!row) {
                //         flag = this.setSelectExpers(this.selectExpers, selection)
                //         if (!flag) {
                //             // this.$Message.warning('选择的类型和已选的不一致')
                //             this.selectExpers = []
                //         }
                //     } else {
                //         flag = this.setSelectExpersRow(this.selectExpers, row)
                //     }
                // }      
                if (!row) {//全选
                    selection.forEach(exper => {
                        // if (this.flagOldExp && this.selectExpers.length > 0) { //  兼容老数据
                        // 原来选择数据默认数组
                        let selExperIds = this.selectExpers.map(exper => exper.ecid);
                        if (!selExperIds.includes(exper.ecid)) {
                            let index = this.experData.findIndex(item => item.ecid == exper.ecid);
                            if (index != -1) {
                                this.experData[index]._checked = true;
                            }
                            this.selectExpers.push(exper)
                            this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.push(exper) // 已选课件禁用
                        }
                        // } else {
                        //     // 单独处理折叠数据
                        //     let collapse = this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.map(exper => exper.ecid)
                        //     if (!collapse.includes(exper.ecid)) {
                        //         let index = this.experData.findIndex(item => item.ecid == exper.ecid);
                        //         if (index != -1) {
                        //             this.experData[index]._checked = true;
                        //         }
                        //         this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.push(exper)
                        //     }
                        // }

                    })



                } else {
                    let index = this.experData.findIndex(item => item.ecid == row.ecid);
                    if (index != -1) {
                        this.experData[index]._checked = true;
                    }
                    // if (this.flagOldExp && this.selectExpers.length) {
                    //     // if (!flag && this.selectExpers.length > 0) {
                    //     //     this.selectExpers = []
                    //     //     this.$Message.warning('选择的类型和已选的不一致,已清空之前选择数据')
                    //     // }
                    //     this.selectExpers.push(row)
                    // } else {
                    this.selectExpers.push(row)
                    this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.push(row)
                    // }
                }
	        	this.formValidate.expDtoList = this.selectExpers.map((exper,index) => {
	        		return {
	        			"ecid": exper.ecid,
					    "orderno": index+1,
					    "percent": 0
	        		}
                })
                if (this.formValidate.expDtoList.length > 0) {
                    this.$refs.formValidate.validateField('expDtoList', err => {
                        return false
                    })
                }
            },
            setSelectExpers (selectExpers, data) {
                let flag = false
                if (selectExpers.length == 0) {
                    flag = true
                } else {
                    selectExpers.forEach(item => {
                        data.forEach(item2 => {
                            if (item.typeCode == item2.typeCode) {
                                flag = true
                            } else {
                                flag = false
                            }
                        })
                    })
                }
                return flag;
            },
            setSelectExpersRow (selectExpers, row) {
                let flag = false
                if (selectExpers.length == 0) {
                    flag = true
                } else {
                    selectExpers.forEach(item => {
                        if (item.typeCode == row.typeCode) {
                            // this.selectExpers.push(row)
                            flag = true
                        } else {
                            flag = false
                            // let index = selectExpers.indexOf(row.typeCode)
                            // if (index > -1) {
                            //     this.selectExpers.splice(index, 1)
                            // }
                        }
                    })
                }
                return flag
            },
	        removeExper(selection,row){
	        	if(!row){//全选
	        		this.experData.forEach(exper => {
        				exper._checked = false;
	        			this.delSelExper(exper.ecid);
	        		})
	        	}else{
	        		let listExper = this.experData.filter(item => item.id == row.id);
    				if(listExper.length > 0){
    					listExper[0]._checked = false;
    				}
					this.delSelExper(row.ecid);
	        	}
	        },
            delSelExper (ecid) {
                // if (this.flagOldExp && this.selectExpers.length) {
                    let delExperIndex = this.selectExpers.findIndex(items => items.ecid === ecid)
                if (delExperIndex >= 0) {
                    this.selectExpers.splice(delExperIndex, 1);
                }
                    let deleteIndex = this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.findIndex(items => items.ecid === ecid)
                if (deleteIndex >= 0) {
                    this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.splice(deleteIndex, 1);
                }
                // } else {
                //     let deleteIndex = this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.findIndex(items => items.ecid === ecid)
                //     if (deleteIndex >= 0) {
                //         this.collapse[this.firstIndex].courseexpchapterDtoList[this.secondIndex].expOutDtoList.splice(deleteIndex, 1);
                //     }
                // }
                this.formValidate.expDtoList = this.selectExpers.map((exper, index) => {
                    return {
                        "ecid": exper.ecid,
                        "orderno": index + 1,
                        "percent": 0
                    }
                })
                if (this.formValidate.expDtoList.length == 0) {
                    this.$refs.formValidate.validateField('expDtoList', err => {
                        return true
                    })
                }
            },
	        addCourse(addData,id){
                let data = JSON.parse(JSON.stringify(this.formValidate));
                if (this.flagOldExp && this.selectExpers.length) {
                    data.expDtoList = this.selectExpers.map((exper, index) => {
                        return {
                            "ecid": exper.ecid,
                            "orderno": index + 1,
                            "percent": 0
                        }
                    })
                } else {
                    data.expDtoList = addData
                }
	        	data.courseLogo = this.useImagePath;
                data.filePath = this.useImagePath;
                data.chapterId = id;

                if (this.mergeLabels.length > 0 || this.formValidate.labels.length > 0) {
						data.labels = this.mergeLabels.join(';');
                }else{
                   data.labels = ''
                }
	        	addCourse(data).then(data => {
	        		if(data.code == 1){
	        			this.$Message.success({
                            content:'新增课程成功！',
                            duration:3,
                        });
                        this.addLabelsArr = []
                        this.handleReset('formValidate')
                        setTimeout(()=>{
                            this.returnCourse()
                        })
	        		}else{
	        			this.$Message.error(data.message)
	        		}
	        		this.creatExperLoading = false;
	        	}).catch(error => {
	        		this.$Message.error('新增课程失败，请稍后再试')
	        		this.creatExperLoading = false;
	        	})
	        },
	        modifyCourse(addData,id){
	        	let data = JSON.parse(JSON.stringify(this.formValidate));
	        	data.courseLogo = this.useImagePath;
                data.filePath = this.useImagePath;
                
                if (this.flagOldExp && this.selectExpers.length) {
                    data.expDtoList = this.selectExpers.map((exper, index) => {
                        return {
                            "ecid": exper.ecid,
                            "orderno": index + 1,
                            "percent": 0
                        }
                    })
                } else {
                    data.expDtoList = addData
                }
                data.chapterId = id
               if (this.mergeLabels.length > 0 || this.formValidate.labels.length > 0 ) {
					data.labels = this.mergeLabels.join(';');
                } else {
                   data.labels = '' 
                }
	        	updateCourse(data.ccid,data).then(data => {
					if (data.code == 1) {
						this.$Message.success({
                            content:'修改课程成功！',
                            duration:3,
                        });
						setTimeout(()=>{
                            this.returnCourse()
                        })
					} else {
						this.$Message.error(data.message)
					}
                    this.addLabelsArr = []
					this.creatExperLoading = false;
				}).catch(error => {
					this.$Message.error('修改课程失败，请稍后再试')
					this.creatExperLoading = false;
				})
            },
            addChapters (name) {
                 let data = {}
                if (this.isCreate) {
                    data = this.childrenCollapse1([])
                } else {
                    data = this.childrenCollapse1(this.collapse)
                }
                 addOrUpdateChapter(data).then(res => {
                    if (res.code == 1) {
                        let resarr = res.data.courseexpchapterDtoList
                        let resIdData = this.childrenCollapse1(resarr)
                        this.summaryData(name,resIdData.courseexpchapterDtoList, res.data.id)
                     
                    }
                 })  
            },
            summaryData (name, resIdData, id) {
                let sumData = []
                resIdData.forEach((item,index) => {
                    item.courseexpchapterDtoList.forEach((item2,index2)=> {
                        item2.courseexpchapterDtoList.forEach((item3, index3) => {
                        sumData.push(item3)
                       })
                    })
                })
               this.saveAddCourse(name,sumData,id)  
            },
            childrenCollapse1 (resArr) {
                let resArrD = resArr.length > 0 ? resArr : []
                let data = {
                    name: '壳子',
                    orderby: 0,
                    courseexpchapterDtoList: [],
                }
                if (this.getChapterID || this.getChapterCcid) {
                    data.ccid = this.getChapterCcid
                    data.id = this.getChapterID
                }
                this.collapse.forEach((item, index) => {
                    if (resArrD.length > 0) {
                        if (!this.isCreate) {
                            data.courseexpchapterDtoList.push({
                                name: item.name,
                                orderby: index + 1,
                                parentid: resArrD[index].parentid || '',
                                id:resArrD[index].id || '',
                                courseexpchapterDtoList: this.childrenCollapse2(item.courseexpchapterDtoList, resArrD[index].courseexpchapterDtoList)
                            })
                        } else {
                            data.courseexpchapterDtoList.push({
                                name: item.name,
                                orderby: index + 1,
                                courseexpchapterDtoList: this.childrenCollapse2(item.courseexpchapterDtoList, resArrD[index].courseexpchapterDtoList)
                            })
                        }
                    } else {
                        data.courseexpchapterDtoList.push({
                            name: item.name,
                            orderby: index + 1,
                            courseexpchapterDtoList: this.childrenCollapse2(item.courseexpchapterDtoList, [])
                        })
                    }
                })
                return data;
            },
            childrenCollapse2 (val,resArr) {
                console.log('🚀 ~ file: createCourse.vue:1497 ~ childrenCollapse2 ~ resArr', resArr)
                let result = []
                val.forEach((item, index) => {
                    if (resArr.length > 0) {
                        if (!this.isCreate) {
                            result.push({
                                name: item.name,
                                orderby: index + 1,
                                parentid: resArr[index].parentid || '',
                                id:resArr[index].id || '',
                                courseexpchapterDtoList: this.childrenCollapse3(item.expOutDtoList, resArr[index].id)
                            })
                        } else {
                        result.push({
                        name: item.name,
                        orderby: index + 1,
                        courseexpchapterDtoList: this.childrenCollapse3(item.expOutDtoList,resArr[index].id)
                    })
                     }
                    } else {
                     result.push({
                        name: item.name,
                        orderby: index + 1,
                        courseexpchapterDtoList: this.childrenCollapse3(item.expOutDtoList,'')
                    })
                   }
                })
               return result
            },
            childrenCollapse3 (val,id) {
                let result = []
                val.forEach((item, index) => {
                    if (id) {
                        result.push({
                            "ecid": item.ecid,
                            "orderno": index + 1,
                            "percent": 0,
                            chapterId: id || ''

                        })
                    } else {
                        result.push({
                            "ecid": item.ecid,
                            "orderno": index + 1,
                            "percent": 0,

                        })
                    }
                })
                return result;
            },
            validateCollapseFormName () {
                let result = {
                    flag: false,
                    type:1
                }
                this.collapse.forEach(item => {
                    if (item.name == '') {
                        result.flag = true
                         result.type = 1
                        //  this.$Message.warning('请填写完整的章节名称')
                        return 
                    } else {
                        item.courseexpchapterDtoList.forEach(item2 => {
                            if (item2.name == '') {
                                result.flag = true
                                result.type = 2
                                return
                            }
                        })
                    }
                })
                return result;
            },
            saveCourse (name) {
                if (!this.flagOldExp) {
                    this.$refs.collapseForm.addFrom()
                }
               let resValidate = this.validateCollapseFormName()
                if (resValidate.flag) {
                    if (resValidate.type == 1) {
                        this.$Message.warning('请填写完整的章节名称')
                    } else {
                        this.$Message.warning('请填写完整的小节名称')
                    }
                    return;
                }
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if (this.flagOldExp) {
                            if (this.isCreate) {
                                this.addCourse();
                            } else {
                                this.modifyCourse();
                            }
                            if (this.addLabelsArr.length > 0) {
                                this.dictEntrysSave()
                            }
                        } else {
                            if (this.collapse.length > 0) {
                                this.addChapters(name)
                            }
                        }
                    } else {
                        this.creatExperLoading = false;
                    }
                }).catch(error => {
                    this.creatExperLoading = false;
                })
            },
            saveAddCourse (name,data,id) {
                this.creatExperLoading = true;
	        	this.$refs[name].validate((valid) => {
                    if (valid) {
                    	if(this.isCreate){
			        		this.addCourse(data,id);
			        	}else{
			        		this.modifyCourse(data,id);
			        	}
                        if (this.addLabelsArr.length > 0) {
					        this.dictEntrysSave()
                        }
                    }else{
                    	this.creatExperLoading = false;
                    }
                }).catch(error => {
                    this.creatExperLoading = false;
                })
            },
	        // 重置
            handleReset (name) {
                this.useImagePath =  '';
                this.selectExpers = [];
                this.formValidate.abc = '';
                this.mergeLabels = [],
				this.addLabelsArr = [],
                this.collapse = [{
                    name: '第1章',
                    courseexpchapterDtoList: [{
                        name: '第1节',
                        orderby: 0,
                        expOutDtoList: []
                    }]
                }],
                this.$refs[name].resetFields();   
                },
            // 课件类型
            handleExpType(val){
                if(val === 0){
                    return '实操课件'
                }else if(val === 1){
                    return '理论课件'
                }else if(val === 2){
                    return '文本课件'
                }else {
                    return '实操课件'
                }
            },
            // 课件标签
            handleExpLabels (val) {
                let result = []
                let initArr = val.split(';')
                initArr.forEach(item => {
                    this.expClassifyTag.forEach(initItem => {
                        if (item == initItem.dictid) {
                            result.push(initItem.dictname)
                        }
                    })
                })
               return result.join()
            },
            handlePublic(val){
                let obj = {
                    text:'',
                    color:'#8d95a6'
                }
                switch (val){
                    case 'person':
                    case 0:
                    case '0':
                        return obj = {
                            text:'个人',
                            color:'rgb(255, 165, 0)',
                        }
                        break;
                    case 'company':
                    case 1:
                    case '1':
                        return obj = {
                            text:'单位',
                            color:'rgb(50, 205, 50)',
                        }
                        break;
                    case 'system':
                    case 2:
                    case '2':
                        return obj = {
                            text:'系统',
                            color:'rgb(65, 105, 225)',
                        }
                        break;
                  case 'range':
                  case 3:
                  case '3':
                    return obj = {
                      text:'平台',
                      color:'#ff61f4',
                    }
                    break;
                }
            },
            changeTypeCode(){
                if (this.addExperModel) {
                    this.getExpListNotPrivates()
                } else {
                    this.selectExpers.forEach(item => {
                        this.handleExperClose(item.ecid)
                    })
                    this.selectExpers = [];
                }
            },
            changePublic(val){
            	if(val == 1 && this.isCreate){
            		if(this.useImageVisibility == 'private'){
            			this.formValidate.topology = '';
            			this.useImagePath =  '';
            		}
            		this.selectExpers = this.selectExpers.filter(exper => exper.isPublic != 0);
            		this.formValidate.expDtoList = this.selectExpers.map((exper,index) => {
		        		return {
		        			"ecid": exper.ecid,
						    "orderno": index+1,
						    "percent": 0
		        		}
		        	})
            	}
            },
            changeDirection(val){
				if(val == 'All'){
					this.expClassifyLevel2 = this.expClassify.filter(dict => dict.parentid);
				}else{
					this.expClassifyLevel2 = this.expClassify.filter(dict => dict.parentid == val);
				}
				this.formValidate.type = '';
                // this.selectExpers.forEach(item=>{
                //     this.handleExperClose(item.ecid)
                // })

			},
        }
    }
</script>
<style scoped>
.add_icon{
	position: absolute;
	right: -23px;
	top:8px;
    cursor:pointer;
}
.width_150{
    max-width: 150px;
    overflow: hidden;
}

.width_150.ivu-tag >>> .ivu-tag-text{
    max-width: 100px !important;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
    display: inline-block;
}
.width_150.ivu-tag>>> .ivu-icon-ios-close {
    position: relative;
    top: -9px !important;
}
    .page-content{
        background-color: var(--card-body-bgcolor);
        border-radius: 10px;
    }
    .img-header{
        display: flex;
        justify-content: space-between;
        padding: 20px 20px 0 20px;
    }
    .addressIcon{
        display: inline-block;
        height: 14px;
        width: 12px;
        background: url("../../assets/globalIcon/addressIcon.png") no-repeat center;
        background-size: 100% 100%;
        margin-bottom: -1px;
    }
    .content-wrap{
        overflow-x: hidden;
        overflow-y: auto;
        padding: 0 20px;
        height: calc(100% - 96px);
    }
    .chose-wrap{
        display: flex;
        justify-content: space-between;
        padding: 3px 8px;
        background-color: var(--table-tr-hover-color);
        align-items: center;
        margin-top: 10px;
    }
    .chose-name{
        width: 300px;
        display: inline-block;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space:nowrap;
    }
    .chose-s-icon{
        width: 15px;
        height: 17px;
        display: inline-block;
        margin-bottom: 1px;
        margin-right: 10px;
    }
    .chose-s2-icon{
        width: 13px;
        height: 15px;
        display: inline-block;
        margin-bottom: 1px;
        margin-right: 10px;
    }
    .deviceDrawer{
        position: relative;
    }
</style>
<style>
    .deviceDrawer .ivu-drawer-body{
        overflow: inherit;
    }
    .content-wrap .ivu-form-item{
        margin-bottom: 20px;
    }
    .template-lable .ivu-form-item-label::before{
        content: '*';
        display: inline-block;
        margin-right: 4px;
        line-height: 1;
        font-family: SimSun;
        font-size: 12px;
        color: #ed4014;
    }
</style>
